package com.simon.seckill.controller;

import com.simon.seckill.Exceptions.SeckillExceptions;
import com.simon.seckill.cache.SeckillSuccessTokenCache;
import com.simon.seckill.service.ProductService;
import com.simon.seckill.unit.RestResultUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/api/")
public class ApiController {

    @Autowired
    private RestResultUnit restResultUnit;

    @Autowired
    private ProductService productService;

    @Autowired
    private SeckillSuccessTokenCache seckillSuccessTokenCache;

    /**
     * 查询系统时间
     *
     * */
    @RequestMapping(value = "time/now")
    public RestResultUnit nowTime() {
        restResultUnit.ok().put("data", System.currentTimeMillis());
        return restResultUnit;
    }

    @RequestMapping("seckill/{id}/path")
    public RestResultUnit seckillPath(@PathVariable("id") Integer id) {

        String randomName = productService.getProductRandomName(id);

        restResultUnit.ok().put("data", randomName);
        return restResultUnit;
    }

    @RequestMapping("seckill")
    public RestResultUnit seckill(String phone, String randomName) {

        try {
            productService.seckill(phone, randomName);
            restResultUnit.ok().put("data", phone);
        } catch (SeckillExceptions e) {
            restResultUnit.error(1, e.getErrorInfo());
        }
        return restResultUnit;
    }

    @RequestMapping(value = "seckill/result", method = RequestMethod.POST)
    public RestResultUnit result(String phone, String randomName) {
        // 查询下单token
        String token = seckillSuccessTokenCache.queryToken(phone, randomName);
        restResultUnit.ok().put("data", token);
        return restResultUnit;
    }

    @RequestMapping(value = "seckill/order", method = RequestMethod.POST)
    public RestResultUnit order(String token, String phone, Integer goodId) {
        try {
            restResultUnit.ok().put("data", productService.order(phone, goodId, token));
        }catch (SeckillExceptions e) {
            restResultUnit.error(1, e.getErrorInfo());
        }
        return restResultUnit;
    }
}
